package com.kunbo.offer.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import sun.misc.BASE64Decoder;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.kunbo.offer.dao.FanSupplementParamDao;
import com.kunbo.offer.entity.CapabilityParam;
import com.kunbo.offer.entity.FanBaseParameter;
import com.kunbo.offer.entity.FanSupplementParam;
import com.kunbo.offer.entity.ProductMix;
import com.kunbo.offer.service.CapabilityParamService;
import com.kunbo.offer.service.ProductMixService;
import com.kunbo.shop.dao.sort.ProductSortDao;
import com.kunbo.shop.entity.sort.ProductSort;
import com.kunbo.shop.service.sort.ProductSortService;
import com.shuohe.util.returnBean.ReturnBean;

@RestController
@RequestMapping("/productMix/")
public class ProductMixController {
	@Autowired
	private ProductMixService productMixService;

	// 风机性能参数业务层
	@Autowired
	private CapabilityParamService capabilityParamService;
	@Autowired
	private ProductSortService productSortService;
	@Autowired
	private ProductSortDao productSortDao;
	@Autowired
	private FanSupplementParamDao fanSupplementParamDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 
	 * <p>
	 * Title: save
	 * </p>
	 * <p>
	 * Description:新增风机
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("save")
	public ReturnBean save(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		// 参数传递，传风机基础数据和分机配件价格列表数据
		Gson reGson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		String pmData = request.getParameter("pmData").replaceAll("\"\"",
				"null");
		String fbpData = request.getParameter("fbpData").replaceAll("\"\"",
				"null");
		ProductMix productMix = reGson.fromJson(pmData,
				new TypeToken<ProductMix>() {
				}.getType());
		FanBaseParameter fanBaseParameter = reGson.fromJson(fbpData,
				new TypeToken<FanBaseParameter>() {
				}.getType());
		productMixService.save(productMix, fanBaseParameter);
		return new ReturnBean(true, "操作成功");
	}

	/**
	 * 
	 * <p>
	 * Title: saveParts
	 * </p>
	 * <p>
	 * Description:新增风机配件
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("saveParts")
	public ReturnBean saveParts(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		// 参数传递，传风机基础数据和分机配件价格列表数据
		Gson reGson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		String pmData = request.getParameter("pmData").replaceAll("\"\"",
				"null");
		ProductMix productMix = reGson.fromJson(pmData,
				new TypeToken<ProductMix>() {
				}.getType());
		productMixService.save(productMix);
		return new ReturnBean(true, "操作成功");
	}

	/**
	 * 
	 * <p>
	 * Title: getProductTreeById
	 * </p>
	 * <p>
	 * Description:获取风机树形列表
	 * </p>
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("getProductTreeById")
	public ProductMix getProductTreeById(HttpServletRequest request) {
		// Gson reGson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		String id = request.getParameter("id").replaceAll("\"\"", "null");
		return productMixService.getProductTreeById(id);
	}

	/**
	 * <p>
	 * Title: fanModelOffer
	 * </p>
	 * <p>
	 * Description:风机模型报价
	 * </p>
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("fanModelOffer")
	public ReturnBean fanModelOffer(HttpServletRequest request) {
		// Gson reGson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		String modelNumber = request.getParameter("modelNumber").replaceAll(
				"\"\"", "null");
		productMixService.fanModelOffer(modelNumber);
		return new ReturnBean(true, "报价成功");
	}

	// 获取风机性能曲线数据
	@RequestMapping("getEchartsData")
	public Map<String, Object> getEchartsData(HttpServletRequest request) {
		String fanId = request.getParameter("fanId");
		String fanNumber = request.getParameter("fanNumber");
		System.out.println("fanId:" + fanId);
		Map<String, Object> map = capabilityParamService.findByFanNumber(
				fanNumber, fanId);
		ProductSort ps = productSortService.findById(fanId);
		map.put("fanModel", ps);
		return map;

	}

	@RequestMapping(value = "exportPdf", method = RequestMethod.POST)
	@ResponseBody
	public void chartExport(HttpServletResponse response,
			@RequestParam("base64Info") String base64InfoArr,
			@RequestParam("fanSelectParam") String fanSelectParam,
			@RequestParam("fanId") String fanId,
			@RequestParam("fanNumber") String fanNumber,
			@RequestParam(value = "zhijing", required = false) String zhijing)
			throws Exception {
		Gson gson = new Gson();
		List<FanSelectParam> list = gson.fromJson(fanSelectParam,
				new TypeToken<List<FanSelectParam>>() {
				}.getType());
		Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
		BaseFont bf;
		Font font = null;
		float lineHeight1 = (float) 25.0;
		float lineHeight2 = (float) 25.0;
		BaseFont baseFontChinese = BaseFont.createFont("STSong-Light",
				"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		Font fontChinese = new Font(baseFontChinese, 12, Font.NORMAL);
		String exportFilePath = "D:\\选型文档.pdf";
		PdfWriter.getInstance(doc, new FileOutputStream(exportFilePath));
		doc.open();
		String sql = "select * from shop_fan_other_param where fanId='" + fanId
				+ "'";
		Map<String, Object> otherParamMap = jdbcTemplate.queryForMap(sql);// 获取风机其他参数

		PdfPTable customerTable = new PdfPTable(4);// 创建客户表格
		PdfPTable selectTable = new PdfPTable(4);// 选型参数表格
		PdfPTable otherParamTable = new PdfPTable(4);// 风机其他参数列表
		PdfPTable supplementParamTable = new PdfPTable(4);// 风机补充参数列表
		customerTable.setWidthPercentage(90);
		selectTable.setWidthPercentage(90);
		otherParamTable.setWidthPercentage(90);
		supplementParamTable.setWidthPercentage(90);
		PdfPCell selectHeaderCell = new PdfPCell(new Paragraph("风机选型参数",
				fontChinese));
		selectHeaderCell.setColspan(4);
		PdfPCell otherHeaderCell = new PdfPCell(new Paragraph("风机其他参数",
				fontChinese));
		otherHeaderCell.setColspan(4);
		PdfPCell supplementHeaderCell = new PdfPCell(new Paragraph("风机补充参数",
				fontChinese));
		supplementHeaderCell.setColspan(4);
		selectTable.addCell(selectHeaderCell);
		otherParamTable.addCell(otherHeaderCell);
		supplementParamTable.addCell(supplementHeaderCell);
		PdfPCell leftCell1 = new PdfPCell();
		PdfPCell leftCell2 = new PdfPCell();
		PdfPCell otherCell1 = new PdfPCell();
		PdfPCell otherCell2 = new PdfPCell();
		PdfPCell supplementHeaderCell1 = new PdfPCell();
		PdfPCell supplementHeaderCell2 = new PdfPCell();
		int a = 0;
		String miDu = "";
		String zhuangSu = "";
		for (FanSelectParam fsp : list) {
			a++;
			if ("风机密度".equals(fsp.getKey())) {
				miDu = fsp.getValue();
			}
			if ("风机转速".equals(fsp.getKey())) {
				zhuangSu = fsp.getValue();
			}
			leftCell1 = new PdfPCell(new Paragraph(fsp.getKey(), fontChinese));
			leftCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
			leftCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
			leftCell1.setFixedHeight(lineHeight2);
			leftCell2 = new PdfPCell(new Paragraph(fsp.getValue(), fontChinese));
			leftCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
			leftCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
			leftCell2.setFixedHeight(lineHeight2);
			selectTable.addCell(leftCell1);
			selectTable.addCell(leftCell2);
		}
		if (a % 2 != 0) {
			selectTable.addCell(new PdfPCell());
			selectTable.addCell(new PdfPCell());
		}
		int b = 0;
		// 查询风机的基本信息
		ProductSort productSort = productSortDao.findById(fanId);
		if (productSort != null) {
			String[] strOtherCell = new String[] { "产品型号", "产品编码" };
			for (int i = 0; i < strOtherCell.length; i++) {
				otherCell1 = new PdfPCell(new Paragraph(strOtherCell[i],
						fontChinese));
				if (i == 0) {
					otherCell2 = new PdfPCell(new Paragraph(
							productSort.getText(), fontChinese));
				} else {
					otherCell2 = new PdfPCell(new Paragraph(
							productSort.getProductNumber(), fontChinese));
				}
				otherCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
				otherCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
				otherCell1.setFixedHeight(lineHeight2);
				otherCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
				otherCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
				otherCell2.setFixedHeight(lineHeight2);
				otherParamTable.addCell(otherCell1);
				otherParamTable.addCell(otherCell2);
			}
		}
		// 风机其它参数
		for (String key : otherParamMap.keySet()) {
			if (key.equals("midu")) {
				otherCell1 = new PdfPCell(new Paragraph("密度", fontChinese));
				if (StringUtils.isNotBlank(zhijing)) {
					otherCell2 = new PdfPCell(new Paragraph(
							String.valueOf(miDu), fontChinese));
				} else {
					otherCell2 = new PdfPCell(
							new Paragraph(
									String.valueOf(otherParamMap.get(key)),
									fontChinese));
				}
			} else if (key.equals("zhuansu")) {
				otherCell1 = new PdfPCell(new Paragraph("转速", fontChinese));
				if (StringUtils.isNotBlank(zhijing)) {
					otherCell2 = new PdfPCell(new Paragraph(
							String.valueOf(zhuangSu), fontChinese));
				} else {
					otherCell2 = new PdfPCell(
							new Paragraph(
									String.valueOf(otherParamMap.get(key)),
									fontChinese));
				}
			} else if (key.equals("yelunzhijing")) {
				otherCell1 = new PdfPCell(new Paragraph("叶轮直径", fontChinese));
				if (StringUtils.isNotBlank(zhijing)) {
					otherCell2 = new PdfPCell(new Paragraph(
							String.valueOf(zhijing), fontChinese));
				} else {
					otherCell2 = new PdfPCell(
							new Paragraph(
									String.valueOf(otherParamMap.get(key)),
									fontChinese));
				}
			} else if (key.equals("jihao")) {
				otherCell1 = new PdfPCell(new Paragraph("机号", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else {
				continue;
			}
			b++;
			otherCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
			otherCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
			otherCell1.setFixedHeight(lineHeight2);
			// otherCell2 = new PdfPCell(new
			// Paragraph(String.valueOf(otherParamMap.get(key)),fontChinese));
			otherCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
			otherCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
			otherCell2.setFixedHeight(lineHeight2);
			otherParamTable.addCell(otherCell1);
			otherParamTable.addCell(otherCell2);
		}
		if (b % 2 != 0) {
			otherParamTable.addCell(new PdfPCell());
			otherParamTable.addCell(new PdfPCell());
		}
		// 补充参数
		int c = 0;
		List<FanSupplementParam> listFan = fanSupplementParamDao
				.findByFanId(fanId);
		if (listFan != null && listFan.size() > 0) {
			FanSupplementParam fan = listFan.get(0);
			String[] fanNameCell = new String[] { "风机大类", "产品类型", "传动方式",
					"叶片数", "角度", "电机型号", "电机厂家", "电机安装型式", "是否是防爆电机", "防爆等级",
					"额定功率", "额定转速", "额定电压", "额定电流", "电压频率", "功率因数", "防护等级",
					"绝缘等级", "加热带", "电缆长度", "最低使用温度", "最高使用温度", "允许最大使用湿度",
					"允许最大使用海拔", "前轴承型号", "后轴承型号", "电机能效等级", "电机壳体材质", "电机重量",
					"机壳材质", "叶轮材质", "进风口材质", "防护网材质", "标准件" };
			String[] fanCodeCell = new String[] { fan.getJ_fjdl(),
					fan.getJ_cpxh(), fan.getJ_cdfs(), fan.getJ_yps(),
					fan.getJ_jd(), fan.getD_djxh(), fan.getD_djcj(),
					fan.getD_djazxs(), fan.getD_sfsfbdj(), fan.getD_fbdj(),
					fan.getD_edgl(), fan.getD_edzs(), fan.getD_eddy(),
					fan.getD_eddl(), fan.getD_dypl(), fan.getD_glys(),
					fan.getD_fhdj(), fan.getD_jydj(), fan.getD_jrd(),
					fan.getD_dlcd(), fan.getD_zdwd(), fan.getD_zgwd(),
					fan.getD_yxzdsysd(), fan.getD_yxzdsyhb(), fan.getD_qzcxh(),
					fan.getD_hzcxh(), fan.getD_djnxdj(), fan.getD_djkdcz(),
					fan.getD_djzl(), fan.getC_jkcz(), fan.getC_ylcz(),
					fan.getC_jfkcz(), fan.getC_fhwcz(), fan.getC_bzj() };
			for (int i = 0; i < fanNameCell.length; i++) {
				supplementHeaderCell1 = new PdfPCell(new Paragraph(fanNameCell[i],
						fontChinese));
				supplementHeaderCell2 = new PdfPCell(new Paragraph(fanCodeCell[i],
						fontChinese));
				supplementHeaderCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
				supplementHeaderCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
				supplementHeaderCell1.setFixedHeight(lineHeight2);
				supplementHeaderCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
				supplementHeaderCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
				supplementHeaderCell2.setFixedHeight(lineHeight2);
				supplementParamTable.addCell(supplementHeaderCell1);
				supplementParamTable.addCell(supplementHeaderCell2);
			}
			if (c % 2 != 0) {
				supplementParamTable.addCell(new PdfPCell());
				supplementParamTable.addCell(new PdfPCell());
			}
		}
		customerTable.setSpacingBefore(30);
		doc.add(customerTable);
		selectTable.setSpacingBefore(30);
		selectTable.setSpacingAfter(30);
		doc.add(selectTable);
		doc.add(otherParamTable);
		// 补充参数增加到doc中
		supplementParamTable.setSpacingBefore(30);
		supplementParamTable.setSpacingAfter(30);
		doc.add(supplementParamTable);
		// System.out.println("获取到的图片编码为："+base64InfoArr);
		System.out.println("风机选型参数：" + fanSelectParam);
		writePngToPdfFile(doc, base64InfoArr);
		// 将外形图插入到导出的pdf中
		createOutsideView(doc, fanId);
		// 将外形图的参数插入到pdf中
		Double blowingRate = Double.parseDouble(list.get(0).getValue());// 获取选型风量
		generateOVParamToPdf(doc, fanNumber, blowingRate);
		doc.close();
		// 导出pdf文件
		File file = new File(exportFilePath);
		if (file.exists()) {
			response.setContentType("application/force-download");// 设置强制下载不打开
			// response.addHeader("Content-Disposition", "attachment;fileName="
			// + fileName);// 设置文件名
			response.setHeader(
					"Content-Disposition",
					"attachment; fileName=" + "选型文档.pdf" + ";"
							+ "filename*=utf-8''"
							+ URLEncoder.encode("选型文档.pdf", "UTF-8")); // 设置中文名称并且解决中文乱码问题
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
				System.out.println("success");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@RequestMapping(value = "exportPdf2", method = RequestMethod.POST)
	@ResponseBody
	public void chartExport2(HttpServletResponse response,
			@RequestParam("base64Info") String base64InfoArr,
			@RequestParam("fanSelectParam") String fanSelectParam,
			@RequestParam("fanId") String fanId,
			@RequestParam("fanNumber") String fanNumber) throws Exception {
		Gson gson = new Gson();
		List<FanSelectParam> list = gson.fromJson(fanSelectParam,
				new TypeToken<List<FanSelectParam>>() {
				}.getType());
		Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
		float lineHeight2 = (float) 25.0;
		BaseFont baseFontChinese = BaseFont.createFont("STSong-Light",
				"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		// BaseFont baseFontChinese = BaseFont.createFont(
		// "C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,
		// BaseFont.NOT_EMBEDDED);
		Font fontChinese = new Font(baseFontChinese, 8, Font.NORMAL);
		String exportFilePath = "D:\\sel_document.pdf";
		PdfWriter.getInstance(doc, new FileOutputStream(exportFilePath));
		doc.open();
		String sql = "select * from shop_fan_other_param where fanId='" + fanId
				+ "'";
		Map<String, Object> otherParamMap = jdbcTemplate.queryForMap(sql);// 获取风机其他参数

		PdfPTable selectTable = new PdfPTable(4);// 选型参数表格
		PdfPTable otherParamTable = new PdfPTable(4);// 风机其他参数列表

		selectTable.setWidthPercentage(90);
		otherParamTable.setWidthPercentage(90);

		PdfPCell selectHeaderCell = new PdfPCell(new Paragraph(
				"Fan selection parameter", fontChinese));
		selectHeaderCell.setColspan(4);
		PdfPCell otherHeaderCell = new PdfPCell(new Paragraph(
				"Fan other parameter", fontChinese));
		otherHeaderCell.setColspan(4);
		selectTable.addCell(selectHeaderCell);
		otherParamTable.addCell(otherHeaderCell);
		PdfPCell leftCell1 = new PdfPCell();
		PdfPCell leftCell2 = new PdfPCell();
		PdfPCell otherCell1 = new PdfPCell();
		PdfPCell otherCell2 = new PdfPCell();
		int a = 0;
		for (FanSelectParam fsp : list) {
			a++;
			leftCell1 = new PdfPCell(new Paragraph(fsp.getKey()
					.replaceAll("风量", "Air flow")
					.replaceAll("误差范围", "Error range")
					.replaceAll("风机密度", "density").replaceAll("风机转速", "Speed"),
					fontChinese));
			leftCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
			leftCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
			leftCell1.setFixedHeight(lineHeight2);
			leftCell2 = new PdfPCell(new Paragraph(fsp.getValue(), fontChinese));
			leftCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
			leftCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
			leftCell2.setFixedHeight(lineHeight2);
			selectTable.addCell(leftCell1);
			selectTable.addCell(leftCell2);
		}
		if (a % 2 != 0) {
			selectTable.addCell(new PdfPCell());
			selectTable.addCell(new PdfPCell());
		}
		int b = 0;
		for (String key : otherParamMap.keySet()) {
			if (key.equals("id")) {
				continue;
			} else if (key.equals("fanId")) {
				continue;
			} else if (key.equals("uuid")) {
				continue;
			} else if (key.equals("create_user_id")) {
				continue;
			} else if (key.equals("taskid")) {
				continue;
			} else if (key.equals("ceshi1") || key.equals("fengjileixing")
					|| key.equals("xiuzhengyinsu")
					|| key.equals("shifufangbao")
					|| key.equals("fengtongbanhou")
					|| key.equals("fengtongleixing")
					|| key.equals("huanqileixing") || key.equals("fanghuwang")
					|| key.equals("kongjianjiareqi")
					|| key.equals("xiuzhengyinsu_en")
					|| key.equals("fengtongbanhou_en")
					|| key.equals("fengtongleixing_en")
					|| key.equals("huanqileixing_en")
					|| key.equals("fanghuwang_en")
					|| key.equals("jueyuandengji") || key.equals("renzheng")
					|| key.equals("chuandongfangshi")
					|| key.equals("jikebanhou") || key.equals("jikeleixing")
					|| key.equals("jinkoufanghuwang")
					|| key.equals("chukoufanghuwang")
					|| key.equals("chanpinleixing")) {
				continue;
			} else if (key.equals("fengjileixing_en")) {
				otherCell1 = new PdfPCell(
						new Paragraph("Fan type", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
				/*
				 * } else if (key.equals("xiuzhengyinsu_en")) { otherCell1 = new
				 * PdfPCell(new Paragraph("Correction factor", fontChinese));
				 * otherCell2 = new PdfPCell(new Paragraph(
				 * String.valueOf(otherParamMap.get(key)), fontChinese));
				 */
			} else if (key.equals("shifufangbao_en")) {
				otherCell1 = new PdfPCell(new Paragraph("Is explosion proof",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("dianya")) {
				otherCell1 = new PdfPCell(new Paragraph("Voltage", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("pinlv")) {
				otherCell1 = new PdfPCell(new Paragraph("Frequency",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("fanghudengji")) {
				otherCell1 = new PdfPCell(new Paragraph("Protection level",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("fengjianzhuangxingshi")) {
				otherCell1 = new PdfPCell(new Paragraph(
						"Installation Form of Fan", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
				/*
				 * } else if (key.equals("jueyuandengji")) { otherCell1 = new
				 * PdfPCell(new Paragraph("Insulation level", fontChinese));
				 * otherCell2 = new PdfPCell(new Paragraph(
				 * String.valueOf(otherParamMap.get(key)), fontChinese)); } else
				 * if (key.equals("fengtongbanhou_en")) { otherCell1 = new
				 * PdfPCell(new Paragraph( "Thickness of air duct",
				 * fontChinese)); otherCell2 = new PdfPCell(new Paragraph(
				 * String.valueOf(otherParamMap.get(key)), fontChinese)); } else
				 * if (key.equals("fengtongleixing_en")) { otherCell1 = new
				 * PdfPCell(new Paragraph("Air duct type", fontChinese));
				 * otherCell2 = new PdfPCell(new Paragraph(
				 * String.valueOf(otherParamMap.get(key)), fontChinese)); } else
				 * if (key.equals("huanqileixing_en")) { otherCell1 = new
				 * PdfPCell(new Paragraph("Ventilation type", fontChinese));
				 * otherCell2 = new PdfPCell(new Paragraph(
				 * String.valueOf(otherParamMap.get(key)), fontChinese)); } else
				 * if (key.equals("fanghuwang_en")) { otherCell1 = new
				 * PdfPCell(new Paragraph("Protective net", fontChinese));
				 * otherCell2 = new PdfPCell(new Paragraph(
				 * String.valueOf(otherParamMap.get(key)), fontChinese)); } else
				 * if (key.equals("renzheng")) { otherCell1 = new PdfPCell(new
				 * Paragraph("Authentication", fontChinese)); otherCell2 = new
				 * PdfPCell(new Paragraph(
				 * String.valueOf(otherParamMap.get(key)), fontChinese));
				 */
			} else if (key.equals("chuandongfangshi_en")) {
				otherCell1 = new PdfPCell(new Paragraph("Transmission mode",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("jikebanhou_en")) {
				otherCell1 = new PdfPCell(new Paragraph("Shell thickness",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("jikeleixing_en")) {
				otherCell1 = new PdfPCell(new Paragraph("Chassis type",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("jinkoufanghuwang_en")) {
				otherCell1 = new PdfPCell(new Paragraph(
						"Import protection net", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("chukoufanghuwang_en")) {
				otherCell1 = new PdfPCell(new Paragraph(
						"Export protection net", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("kongjianjiareqi_en")) {
				otherCell1 = new PdfPCell(new Paragraph("Space heater",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("midu")) {
				otherCell1 = new PdfPCell(new Paragraph("density", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("zhuansu")) {
				otherCell1 = new PdfPCell(new Paragraph("Speed", fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("yelunzhijing")) {
				otherCell1 = new PdfPCell(new Paragraph("Impeller diameter",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("jihao")) {
				otherCell1 = new PdfPCell(new Paragraph("Machine number",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			} else if (key.equals("chanpinleixing_en")) {
				otherCell1 = new PdfPCell(new Paragraph("Product type",
						fontChinese));
				otherCell2 = new PdfPCell(new Paragraph(
						String.valueOf(otherParamMap.get(key)), fontChinese));
			}

			otherCell1.setHorizontalAlignment(Element.ALIGN_CENTER);
			otherCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
			otherCell1.setFixedHeight(lineHeight2);
			otherCell2.setHorizontalAlignment(Element.ALIGN_CENTER);
			otherCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
			otherCell2.setFixedHeight(lineHeight2);
			otherParamTable.addCell(otherCell1);
			otherParamTable.addCell(otherCell2);
			b++;
		}
		System.err.println("b的数量为：" + b);
		if (b % 2 != 0) {
			otherParamTable.addCell(new PdfPCell());
			otherParamTable.addCell(new PdfPCell());
		}
		selectTable.setSpacingBefore(30);
		selectTable.setSpacingAfter(30);
		doc.add(selectTable);
		doc.add(otherParamTable);
		// System.out.println("获取到的图片编码为："+base64InfoArr);
		System.out.println("风机选型参数：" + fanSelectParam);
		writePngToPdfFile(doc, base64InfoArr);
		// 将外形图插入到导出的pdf中
		createOutsideView(doc, fanId);
		// 将外形图的参数插入到pdf中
		Double blowingRate = Double.parseDouble(list.get(0).getValue());// 获取选型风量
		generateOVParamToPdf(doc, fanNumber, blowingRate);
		doc.close();
		// 导出pdf文件
		File file = new File(exportFilePath);
		if (file.exists()) {
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition", "attachment; fileName="
					+ "sel_document.pdf" + ";" + "filename*=utf-8''"
					+ URLEncoder.encode("sel_document.pdf", "UTF-8")); // 设置中文名称并且解决中文乱码问题
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
				System.out.println("success");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private int getPercent2(float h, float w) {
		int p = 0;
		float p2 = 0.0f;
		p2 = 530 / w * 100;
		p = Math.round(p2);
		return p;
	}

	// 输入流读取到输出流
	// private void copy(InputStream input,OutputStream outputString){
	// byte [] but = new byte[1024];
	// try {
	// while(input.read()!=-1){
	// int by = input.read(but);
	// outputString.write(but, 0, by);
	// outputString.flush();
	// }
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	private void copy(BufferedInputStream input,
			BufferedOutputStream outputString) {
		byte[] but = new byte[1024];

		try {
			int by = input.read(but);
			while (by != -1) {
				outputString.write(but, 0, by);
				by = input.read(but);
				// outputString.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * <p>
	 * Title: writePngToPdfFile
	 * </p>
	 * <p>
	 * Description:将echarts加入到pdf中
	 * </p>
	 * 
	 * @param doc
	 * @param base64Info
	 * @param pngPath
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private boolean writePngToPdfFile(Document doc, String base64InfoArr)
			throws Exception {
		String echartsPngPath = "";
		String[] arrBase64 = base64InfoArr.split("&&");
		Image image = null;
		String imagePath = null;
		OutputStream output = null;
		// 读取图片流
		BufferedImage img = null;
		for (int i = 0; i < arrBase64.length; i++) {
			// String newFileName="";
			String base64Info;
			// newFileName = System.currentTimeMillis() + ".pdf";
			// String newPngName = newFileName.replaceFirst(".pdf", ".png");
			imagePath = "D:\\echartsPng\\" + System.currentTimeMillis()
					+ ".png";
			base64Info = arrBase64[i].replaceAll(" ", "+");
			BASE64Decoder decoder = new BASE64Decoder();
			String[] arr = base64Info.split("base64,");
			byte[] buffer;
			try {
				buffer = decoder.decodeBuffer(arr[1]);
			} catch (IOException e) {
				throw new RuntimeException();
			}
			try {

				output = new FileOutputStream(new File(imagePath));// 生成png文件
				output.write(buffer);
				output.flush();
				image = Image.getInstance(imagePath);
				float heigth = image.getHeight();
				float width = image.getWidth();
				int percent = this.getPercent2(heigth, width);
				// 以下两行设置可导致第二张和第三张图无法显示
				// image.setAlignment(Image.MIDDLE);
				// image.setAlignment(Image.TEXTWRAP);
				image.scalePercent(percent + 3);
				doc.add(image);

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				output.close();
				return false;

			}
			output.close();
		}
		// String imageFolderPath = "D:\\echartsPng\\";
		// File file = new File(imageFolderPath);
		// File[] files = file.listFiles();
		// for (File file1 : files) {
		// if (file1.getName().endsWith(".png")
		// || file1.getName().endsWith(".jpg")
		// || file1.getName().endsWith(".gif")
		// || file1.getName().endsWith(".jpeg")
		// || file1.getName().endsWith(".tif")) {
		// // System.out.println(file1.getName());
		// imagePath = imageFolderPath + file1.getName();
		// System.out.println(file1.getName());
		// // 读取图片流
		// img = ImageIO.read(new File(imagePath));
		// // 根据图片大小设置文档大小
		// //doc.setPageSize(new Rectangle(img.getWidth(), img
		// //.getHeight()));
		// // 实例化图片
		// image = Image.getInstance(imagePath);
		// int percent = this.getPercent2(img
		// .getHeight(), img.getWidth());
		// image.scalePercent(percent);
		// // 添加图片到文档
		// doc.add(image);
		// }
		// }
		return true;

	}

	/**
	 * 
	 * <p>
	 * Title: createOutsideView
	 * </p>
	 * <p>
	 * Description: 生成风机外形图到pdf
	 * </p>
	 * 
	 * @param doc
	 * @param fanId
	 * @throws Exception
	 */
	private void createOutsideView(Document doc, String fanId) throws Exception {
		String sql = "select * from shop_fan_file where fan_number='" + fanId
				+ "' and fileType='外形图' ";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);// 获取风机其他参数
		if (list.size() == 0) {
			return;
		}
		String imagePath = (String) list.get(0).get("filePath");
		Image image = Image.getInstance(imagePath);
		float heigth = image.getHeight();
		float width = image.getWidth();
		int percent = this.getPercent2(heigth, width);
		image.scalePercent(percent + 3);
		doc.add(image);
	}

	/**
	 * 
	 * <p>
	 * Title: generateOVParamToPdf
	 * </p>
	 * <p>
	 * Description:生成外形图参数到pdf
	 * </p>
	 * 
	 * @throws Exception
	 */
	private void generateOVParamToPdf(Document doc, String fanNumber,
			Double blowingRate) throws Exception {
		CapabilityParam finCp = null;// 存放最终获取到的风机性能参数
		// 1.根据风机编号获取性能参数
		List<CapabilityParam> list = capabilityParamService
				.findByFanNumber(fanNumber);
		// 差值实始化
		Double diffNum = Math.abs(list.get(0).getFlux() - blowingRate);
		// 最终结果
		Double result = list.get(0).getFlux();
		for (CapabilityParam cp : list) {
			Double diffNumTemp = Math.abs(cp.getFlux() - blowingRate);
			if (diffNumTemp < diffNum) {
				diffNum = diffNumTemp;
				result = cp.getFlux();
				finCp = cp;
			}
		}
		if (null == finCp) {
			finCp = list.get(0);
		}
		System.out.println(result);
		System.out.println(finCp);
		PdfPTable ovDataTable = new PdfPTable(10);// 外形数据表格
		ovDataTable.setWidthPercentage(99);
		PdfPCell F1 = new PdfPCell(new Paragraph("F1"));
		PdfPCell F1V = new PdfPCell(new Paragraph(finCp.getF1()));
		PdfPCell F2 = new PdfPCell(new Paragraph("F2"));
		PdfPCell F2V = new PdfPCell(new Paragraph(finCp.getF2()));
		PdfPCell F3 = new PdfPCell(new Paragraph("F3"));
		PdfPCell F3V = new PdfPCell(new Paragraph(finCp.getF3()));
		PdfPCell F4 = new PdfPCell(new Paragraph("F4"));
		PdfPCell F4V = new PdfPCell(new Paragraph(finCp.getF4()));
		PdfPCell F5 = new PdfPCell(new Paragraph("F5"));
		PdfPCell F5V = new PdfPCell(new Paragraph(finCp.getF5()));
		PdfPCell F6 = new PdfPCell(new Paragraph("F6"));
		PdfPCell F6V = new PdfPCell(new Paragraph(finCp.getF6()));
		PdfPCell F7 = new PdfPCell(new Paragraph("F7"));
		PdfPCell F7V = new PdfPCell(new Paragraph(finCp.getF7()));
		PdfPCell F8 = new PdfPCell(new Paragraph("F8"));
		PdfPCell F8V = new PdfPCell(new Paragraph(finCp.getF8()));
		PdfPCell F9 = new PdfPCell(new Paragraph("F9"));
		PdfPCell F9V = new PdfPCell(new Paragraph(finCp.getF9()));
		PdfPCell F10 = new PdfPCell(new Paragraph("F10"));
		PdfPCell F10V = new PdfPCell(new Paragraph(finCp.getF10()));
		PdfPCell F11 = new PdfPCell(new Paragraph("F11"));
		PdfPCell F11V = new PdfPCell(new Paragraph(finCp.getF11()));
		PdfPCell F12 = new PdfPCell(new Paragraph("F12"));
		PdfPCell F12V = new PdfPCell(new Paragraph(finCp.getF12()));
		PdfPCell F13 = new PdfPCell(new Paragraph("F13"));
		PdfPCell F13V = new PdfPCell(new Paragraph(finCp.getF13()));
		PdfPCell F14 = new PdfPCell(new Paragraph("F14"));
		PdfPCell F14V = new PdfPCell(new Paragraph(finCp.getF14()));
		PdfPCell F15 = new PdfPCell(new Paragraph("F15"));
		PdfPCell F15V = new PdfPCell(new Paragraph(finCp.getF15()));
		PdfPCell F16 = new PdfPCell(new Paragraph("F16"));
		PdfPCell F16V = new PdfPCell(new Paragraph(finCp.getF16()));
		PdfPCell F17 = new PdfPCell(new Paragraph("F17"));
		PdfPCell F17V = new PdfPCell(new Paragraph(finCp.getF17()));
		PdfPCell F18 = new PdfPCell(new Paragraph("F18"));
		PdfPCell F18V = new PdfPCell(new Paragraph(finCp.getF18()));
		PdfPCell F19 = new PdfPCell(new Paragraph("F19"));
		PdfPCell F19V = new PdfPCell(new Paragraph(finCp.getF19()));
		PdfPCell F20 = new PdfPCell(new Paragraph("F20"));
		PdfPCell F20V = new PdfPCell(new Paragraph(finCp.getF20()));
		ovDataTable.addCell(F1);
		ovDataTable.addCell(F1V);
		ovDataTable.addCell(F2);
		ovDataTable.addCell(F2V);
		ovDataTable.addCell(F3);
		ovDataTable.addCell(F3V);
		ovDataTable.addCell(F4);
		ovDataTable.addCell(F4V);
		ovDataTable.addCell(F5);
		ovDataTable.addCell(F5V);
		ovDataTable.addCell(F6);
		ovDataTable.addCell(F6V);
		ovDataTable.addCell(F7);
		ovDataTable.addCell(F7V);
		ovDataTable.addCell(F8);
		ovDataTable.addCell(F8V);
		ovDataTable.addCell(F9);
		ovDataTable.addCell(F9V);
		ovDataTable.addCell(F10);
		ovDataTable.addCell(F10V);
		ovDataTable.addCell(F11);
		ovDataTable.addCell(F11V);
		ovDataTable.addCell(F12);
		ovDataTable.addCell(F12V);
		ovDataTable.addCell(F13);
		ovDataTable.addCell(F13V);
		ovDataTable.addCell(F14);
		ovDataTable.addCell(F14V);
		ovDataTable.addCell(F15);
		ovDataTable.addCell(F15V);
		ovDataTable.addCell(F16);
		ovDataTable.addCell(F16V);
		ovDataTable.addCell(F17);
		ovDataTable.addCell(F17V);
		ovDataTable.addCell(F18);
		ovDataTable.addCell(F18V);
		ovDataTable.addCell(F19);
		ovDataTable.addCell(F19V);
		ovDataTable.addCell(F20);
		ovDataTable.addCell(F20V);
		doc.add(ovDataTable);

	}

}

class FanSelectParam {
	private String key;
	private String value;

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public FanSelectParam() {
		super();
		// TODO Auto-generated constructor stub
	}

	public FanSelectParam(String key, String value) {
		this.key = key;
		this.value = value;
	}

}